(function () {

    // var GetUrl = 'http://192.168.0.25:5010/trueMAEC';
    var GetUrl = 'http://61.155.85.78:5012/trueMAEC';
    var deptid = '{BFA80019-0000-0000-432B-267E0000000E}';

    // 获取 wangEditor 构造函数和 jquery
    var E = window.wangEditor;
    var $ = window.jQuery;

    var idPrefix = 'tags_' + Math.random().toString().replace('.', '') + '_',
        globalNum = 1;

	//生成唯一ID
    function getUniqeId(){
        return idPrefix + (globalNum++); 
    }

    $('#twEditor').append('<div id="paramWrap"></div><div id="tagTem"></div>')
    .append('<div style="margin:20px 20px 0 20px;" class="row" id="tagWrap"></div>').find("#tagWrap")
        .append('<div class="JS_tableWrap"></div>')
        .append('<div class="JS_groupWrap"></div>')
        .append('<div class="JS_fieldWrap"></div>')
        .append('<div class="JS_conditionWrap"></div>')
        .append('<div class="JS_paramWrap"></div>')
        .append('<div class="JS_functionWrap"></div>')
        .append('<div class="JS_styleWrap"></div>')
        .append('<div class="JS_resultWrap"></div></div>');

    var $tableWrap      = $('#tagWrap .JS_tableWrap');
    var $groupWrap      = $('#tagWrap .JS_groupWrap');
    var $fieldWrap      = $('#tagWrap .JS_fieldWrap');
    var $conditionWrap      = $('#tagWrap .JS_conditionWrap');
    var $paramWrap      = $('#tagWrap .JS_paramWrap');
    var $functionWrap   = $('#tagWrap .JS_functionWrap');
    var $styleWrap      = $('#tagWrap .JS_styleWrap');
    var $tagResultWrap     = $('#tagWrap .JS_resultWrap');

    var tagJSON = new Object;


    /*
    "param": [
        {
            "_t1": {
                "condition": {
                    "month": "='7'",
                   guid "mxzbid": "='799600de-b714-4ceb-82e3-8e30a7c90abc'",
                    "year": "='2015'",
                  mdid  "zbid": "='fc822f25-8de9-4274-8a27-fe426f0d3bce'"
                },
                "field": "zl",
                "table": "t_nttj_data_2016"
            }
        }
    ],
    "result": {
        "tag": "sum(_t1)"
    },
    "type": "1"
    */
   
   	//存储对象
	if(!$.fn.GL){
		$.fn.GL = {
			globalObj:{},
			getValue:function(keys){
				if(!this.globalObj[keys]){
					this.globalObj[keys] = {};
				}
				return keys?this.globalObj[keys]:this.globalObj;
			},
			setValue:function(keys,values){
				this.globalObj[keys] = values;
			}
		}
	}
	
    // 生成JSON
    function creatTagJSON(){
        var paramJSON = new Array;

        var group = $groupWrap.find(".label-item.checked");

        var _tableName = $groupWrap.find("table").attr('data-tablename');
        var _groupId = $groupWrap.find("table").attr('data-modelId');
        var _guId = group.attr('data-guid');

        var _year = $conditionWrap.find('select.JS_condYear').val();
        var _month = $conditionWrap.find('select.JS_condMonth').val();
        var _quarter = $conditionWrap.find('select.JS_condQuarter').val();

        _year = typeof _year != 'undefined' ? "='"+_year+"'" : "";
        _month = typeof _month != 'undefined' ? "='"+_month+"'" : "";
        _quarter = typeof _quarter != 'undefined' ? "='"+_quarter+"'" : "";


        var _condition = {'month': _month, 'year': _year, 'season': _quarter, 'mxzbid': "='"+_guId+"'", 'zbid': "='"+_groupId+"'"}


        var params = $fieldWrap.find(".label-item.checked");
        params.each(function() {
            var _paramId = $(this).attr('data-paramid');
            var _fileNote = $(this).text();
            var _fieldName = $(this).attr('data-fieldname');

            var _paramItem = {'table': _tableName, 'note': _fileNote, 'field':_fieldName, 'condition':_condition};
            var paramItem = {};
            paramItem[_paramId] = _paramItem;

            // var p = JSON.parse($(this).val())
            paramJSON.push(paramItem);
        })
        // var modelJSON = new Array;
        // var models = $fieldWrap.find(".table-item");
        // models.each(function(){
        //     var t = $(this).attr('data-modelId');
        //     modelJSON.push(t);
        // })
        var _function = {'tag': $(params[0]).attr('data-paramid')}
//      var _function = {'tag': $functionWrap.find(".JS_inputResult").val()}
        tagJSON = {'param' : paramJSON, 'type': 1,  'result': _function};
    }

    // 清空
    function clearTagsWrap(){
        // $tableWrap.empty();
        $fieldWrap.empty();
        $paramWrap.empty();
        $functionWrap.empty();
        $styleWrap.empty();
        $tagResultWrap.empty();
        //add
        $groupWrap.empty();
        $conditionWrap.empty();
    }

	function verifyMsg(msg){
		//数据验证
    	if(msg && (msg.error==null) && (msg.success==true) && msg.data){
    		//pass
    		return true;
    	}else{
    		//ajax data error
    		return false;
    	}
	}

    // 获取数据库表列表
    function getModelList(argsObj){
        $.ajax({
            type:"POST",
            dataType:"jsonp",
            jsonp:"callback",
            url: GetUrl + "/trueDataController/getModelList.do?deptid="+deptid,
            cache: false,
            async: false,
            success:function(msg){
            	if(!verifyMsg(msg)){
		    		layer.alert('Error at:获取数据库表列表');
		    		return false;
            	}
            	
            	//指标下拉列表数据
                var tables = msg.data;

                var tableOption = '<option>请选择指标</option>';
                //:TODO 这里将tables循环了一次
                for(key in tables){
                	//装载data1
                	var selected = '';
                	if(argsObj && ($.fn.GL.getValue('_editing')===1)){
                		if(tables[key].modelId===$.fn.GL.getValue($.fn.GL.getValue('_openedTagId')).data1){
                			selected = 'selected';
                		}
                	}
                    tableOption += '<option '+selected+' value='+ tables[key].modelId +' data-tableName="'+ tables[key].tableName +'" data-tbKey="'+key+'">'+tables[key].modelName+'</option>';
                }
                // 生成来源表
                var $tableItem = $('<div class="form-inline" style="margin-bottom:10px"><div class="form-group"><label>选择指标: </label><select class="form-control input-sm">'+ tableOption +'</select></div></div>');  
                $tableWrap.empty().append($tableItem);
				
				//select绑定change事件
                $tableWrap.on('change', 'select', function(){
                    var modelId = $(this).val();
                    //数据绑定1
                	var tmpobject = $.fn.GL.getValue('_Current');
                	tmpobject.data1 = modelId;
                	$.fn.GL.setValue('_Current',tmpobject);
                	
                    var tableName =  $(this).find('option:selected').attr("data-tablename")
                    var groupTable = ''
                    //:TODO 这里将tables循环了第二次
//                  for(key in tables){
//                      if(tables[key].modelId == modelId){
//                          // var tabelName = tables[key].tableName;
//                          var groups = tables[key].tyzdxList;
//
//                          var groupItem = '';
//                          for( i in groups ){
//                              // "name": "南通市区组",
//                              var groupHD = groups[i].name;
//                              var groupId = groups[i].id;
//                              var groupBD = '';
//                              var mxs = groups[i].mxlist;
//                              for (j in mxs){
//                                  groupBD += '<span class="label-item" data-guid="'+ mxs[j].guid +'">'+ mxs[j].zbmc +'</span>';
//
//                              }
//                              groupItem += '<tr><th>'+ groupHD +'</th><td>'+ groupBD +'</td></tr>'
//
//                          }
//
//                      }
//                  }
                    // var tabelName = tables[key].tableName;
                    var keyClicked = $(this).find('option:selected').attr("data-tbKey");
                    var groups = tables[keyClicked].tyzdxList;
                    var groupItem = '';
                    //遍历分组
                    for( i in groups ){
                    	
                        // "name": "南通市区组",
                        var groupHD = groups[i].name;
                        var groupId = groups[i].id;
                        var groupBD = '';
                        var mxs = groups[i].mxlist;
                        //遍历组内集合
                        for (j in mxs){
	                    	//装载data2
		                	var checked = '';
		                	if(argsObj && ($.fn.GL.getValue('_editing')===1)){
		                		if(mxs[j].guid===$.fn.GL.getValue($.fn.GL.getValue('_openedTagId')).data2){
		                			checked = 'checked';
		                		}
		                	}
                            groupBD += '<span class="label-item '+checked+'" data-guid="'+ mxs[j].guid +'">'+ mxs[j].zbmc +'</span>';
                        }
                        groupItem += '<tr><th>'+ groupHD +'</th><td>'+ groupBD +'</td></tr>';
                    }
                    
                    groupTable = $('<table data-tablename="'+ tableName +'" data-modelId="'+modelId+'" class="table table-bordered"><colgroup><col width="15%"></colgroup>'+ groupItem +'</table>');
                    $groupWrap.empty().append(groupTable);


					//指标对应要素=>下拉列表对应的字段集合
                    var fieldTable = '';
                    $.ajax({
                        type:"POST",
                        dataType:"jsonp",
                        jsonp:"callback",
                        url: GetUrl + "/trueDataController/getFieldList.do?modelId="+modelId,
                        cache: false,
                        async: false,
                        success:function(field){
                        	if(!verifyMsg(field)){
                        		console.log(field);
					    		console.log('Error at:获取选择要素');
			            	}
                        	
                        	if(field.data && field.data.fields){
	                            var fields = field.data.fields;
	                            var fieldItem = ''
	                            //选择要素
	                            for(f in fields){
	                            	//装载data3
				                	var checked = '';
				                	if(argsObj && ($.fn.GL.getValue('_editing')===1)){
				                		if(('_t'+f)===$.fn.GL.getValue($.fn.GL.getValue('_openedTagId')).data3){
				                			checked = 'checked';
				                		}
				                	}
	                                fieldItem += '<span class="label-item '+checked+'" data-paramid="_t'+ f +'" data-fieldname="'+ fields[f].name +'">'+ fields[f].note +'</span>'
	                            }
	                            fieldTable = $('<table class="table table-bordered"><colgroup><col width="15%" /></colgroup><tr><th>选择要素</th><td>'+ fieldItem +'</td></tr></table>');
	                            $fieldWrap.empty().append(fieldTable);
	                            
                           	}
                        }
                    })

					//选择时间
                    var conditionTable = '';
                    //装载data4
                	var selected = '';
                	var timeType = false,
                	type1 = false,
                	type2 = false,
                	type3 = false;
                	if(argsObj && ($.fn.GL.getValue('_editing')===1)){
                		timeType = $.fn.GL.getValue($.fn.GL.getValue('_openedTagId')).data4.conditionType;
                		type1 = $.fn.GL.getValue($.fn.GL.getValue('_openedTagId')).data4['t_year'];
                		type2 = $.fn.GL.getValue($.fn.GL.getValue('_openedTagId')).data4['t_month'];
                		type3 = $.fn.GL.getValue($.fn.GL.getValue('_openedTagId')).data4['t_quarter'];
                	}
                	
                    var $condItem = $('<div class="form-inline" style="margin-bottom:10px"><div class="form-group"><label>选择时间: </label><select class="form-control input-sm JS_conditionDate">'
                    +'<option>选择时间</option>'
                    +'<option value="year" '+(timeType=='year'?'selected':'')+'>年度</option>'
                    +'<option value="month" '+(timeType=='month'?'selected':'')+'>月度</option>'
                    +'<option value="quarter" '+(timeType=='quarter'?'selected':'')+'>季度</option></select><div style="display:inline-block" class="JS_conditionDateS"></div></div></div>');
                    
                    var condYearOption = '';
                    var condMonthOption = '';
                    for ( var i = 2015; i<=2020; i++ ){
                        condYearOption += '<option value ="'+ i +'" '+((i==type1)?'selected':'')+'>'+ i +'</option>';
                    }
                    for ( var i = 1; i<=12; i++ ){
                        condMonthOption += '<option value ="'+ i +'" '+((i==type2)?'selected':'')+'>'+ i +'</option>';
                    }
                    var conQuarterOption = ('<option value="1" '+(('1'==type3)?'selected':'')+'>第一季度</option>'
                    +'<option value="2" '+(('2'==type3)?'selected':'')+'>第二季度</option>'
                    +'<option value="3" '+(('3'==type3)?'selected':'')+'>第三季度</option>'
                    +'<option value="4" '+(('4'==type3)?'selected':'')+'>第四季度</option>');
                    
                    $conditionWrap.empty().append($condItem);
                    var condYearSelect =$('<select class="form-control input-sm JS_condYear">'+ condYearOption +'</select>');
                    var condMonthSelect = $('<select class="form-control input-sm JS_condYear">'+ condYearOption +'</select><select class="form-control input-sm JS_condMonth">'+ condMonthOption +'</select>');
                    var condQuarterSelect = $('<select class="form-control input-sm JS_condYear">'+ condYearOption +'</select><select class="form-control input-sm JS_condQuarter">'+ conQuarterOption +'</select>');
                    //选择时间下拉change事件
                    $conditionWrap.on('change', ".JS_conditionDate", function(){
                    	var conditionType = $(this).val();
				    	//继续装载时间
				    	var tmpobject = $.fn.GL.getValue('_Current');
				    	var tmpobd = tmpobject.data4;
				    	if(!tmpobd){
				    		tmpobject.data4 = {};
				    	}
				    	tmpobject.data4.conditionType = conditionType;
				    	
                        
                        if(conditionType == 'year'){
                            $conditionWrap.find(".JS_conditionDateS").empty().append(condYearSelect);
                        } else if(conditionType == 'month'){
                            $conditionWrap.find(".JS_conditionDateS").empty().append(condMonthSelect);
                        } else if(conditionType == 'quarter'){
                            $conditionWrap.find(".JS_conditionDateS").empty().append(condQuarterSelect);
                        } else{
                        	$conditionWrap.find(".JS_conditionDateS").empty();
                        }
                        //数据绑定4
                        var t_year = $conditionWrap.find('select.JS_condYear').val();
				        var t_month = $conditionWrap.find('select.JS_condMonth').val();
				        var t_quarter = $conditionWrap.find('select.JS_condQuarter').val();
				    	
				    	
				    	$.fn.GL.setValue('_Current',tmpobject);
                    })
                    $conditionWrap.on('change', ".JS_condYear, .JS_condMonth, .JS_condQuarter", function(){
                        //数据绑定4
                        var t_year = $conditionWrap.find('select.JS_condYear').val();
				        var t_month = $conditionWrap.find('select.JS_condMonth').val();
				        var t_quarter = $conditionWrap.find('select.JS_condQuarter').val();
				    	var tmpobject = $.fn.GL.getValue('_Current');
				    	
				    	tmpobject.data4.t_year=t_year;
				    	tmpobject.data4.t_month=t_month;
				    	tmpobject.data4.t_quarter=t_quarter;
				    	
				    	$.fn.GL.setValue('_Current',tmpobject);
                    })

					var restultTxt = '';
					if(argsObj && ($.fn.GL.getValue('_editing')===1)){
                		restultTxt = $(".tags[data-id='"+$.fn.GL.getValue('_openedTagId')+"']").text();
                		if(typeof restultTxt =='undefined'){
                			restultTxt = '';
                		}
                	}
                    $tagResultWrap.empty().append('<p>结果预览：<span class="JS_btnTagTest btn btn-primary btn-xs">测试</span> <span class="JS_tagValue tags btn">'+restultTxt+'</span></p>');
					
					
					
//                  $functionWrap.empty().append('<p><span>计算公式：</span><input class="JS_inputResult" type="text" placeholder="计算公式" /></p>');	
                })//select change event end

            }
        })
    }//fun end



    $fieldWrap.on("click", ".label-item", function(){
        $fieldWrap.find('.label-item').removeClass('checked');
        $(this).toggleClass('checked');
        var paramKey = $(this).attr("data-paramid")
        $functionWrap.find('input').val(paramKey);
        //数据绑定3
    	var tmpobject = $.fn.GL.getValue('_Current');
    	tmpobject.data3 = paramKey;
    	$.fn.GL.setValue('_Current',tmpobject);
    })

    $groupWrap.on("click", ".label-item", function(){
        $groupWrap.find('.label-item').removeClass('checked');
        $(this).toggleClass('checked');
        //数据绑定2
    	var tmpobject = $.fn.GL.getValue('_Current');
    	tmpobject.data2 = $groupWrap.find('.label-item.checked').attr("data-guid");
    	$.fn.GL.setValue('_Current',tmpobject);
    })

     // 数据测试
    $tagResultWrap.on("click", ".JS_btnTagTest", function(){
        creatTagJSON();
        var a = JSON.stringify(tagJSON);
        console.log(a);
        $.ajax({
            type:"POST",
            data:a,
            dataType:"jsonp",
            jsonp:"callback",
            url:GetUrl + "/formulaController/getResult.do?function="+encodeURIComponent(a),
            success:function(msg){
                var val;
                if(msg.success){
                    val = msg.data[0].tag;
                }else{
                    val = msg.error;
                }
                $tagResultWrap.find(".JS_tagValue").text(val);           
            }
        });
    })


    

    // 选择数据表来源表，返回表字段
    var fieldIndex = 1; //取值索引
    // $tableWrap.on("change", 'select', function(){
    //     var modelId = $(this).find(':selected').val();
    //     var modelJSON = new Array;
    //     var models = $fieldWrap.find(".table-item");
    //     models.each(function(){
    //         var t = $(this).attr('data-modelId');
    //         modelJSON.push(t);
    //     })
    //     // 避免重复表
    //     if($.inArray(modelId, modelJSON) == -1){
    //         getFields(modelId);
    //     }
    // })

    // 点击指标
    function tableClick(event, treeId, treeNode){
        // alert(treeNode.modelId + ", " + treeNode.modelName);
        var modelId = treeNode.modelId;
        var modelJSON = new Array;
        var models = $fieldWrap.find(".table-item");
        models.each(function(){
            var t = $(this).attr('data-modelId');
            modelJSON.push(t);
        })
        // 避免重复表
        if($.inArray(modelId, modelJSON) == -1){
            getFields(modelId);
        }
    }

    // 获取表字段 生成字段列表
    function getFields(modelId){
        $.ajax({
            type:"POST",
            dataType:"jsonp",
            jsonp:"callback",
            url: GetUrl + "/trueDataController/getFieldList.do?modelId="+modelId,
            cache: false,
            async: false,
            success:function(msg){
                var model = msg.data;
                var fieldItem = ''
                var fieldOption = '<option value="">请选择字段</option>';       
                // "desc": "南通地区GDP总值",
                // "fields": [{
                //     "def": "",
                //     "len": "",
                //     "name": "DiQu",
                //     "note": "地区",
                //     "type": "varchar"
                // }]
                // "table": "T_CMS_DATA_GDP", 
                var tableName = model.table;
                var modelName = model.desc;
                var fields = model.fields;

                for(key in fields){
                    fieldOption += '<option value='+ fields[key].name +'>'+fields[key].note+'</option>';
                    fieldItem += '<span class="field-item" data-fieldname="'+ fields[key].name +'">'+ fields[key].note +'</span>';
                }
                
                var $tableItem = $('<tr class="table-item" data-tablename="'+ tableName +'" data-modelId="'+ modelId +'"><td>'+ modelName +'<select style="display:none">'+ fieldOption +'</select></td><td>'+ fieldItem +'</td><td><span class="JS_btnDelTable btn btn-danger btn-xs">删除</span></td></tr>')

                if(!$fieldWrap.find("table").length){
                    var $fieldTable = $('<table class="table table-bordered"><thead><tr><th>指标</th><th>要素</th><th>操作</th></tr></thead><tbody></tbody></table>')
                    $fieldWrap.append($fieldTable);
                }
                $fieldWrap.find("table tbody").append($tableItem);
            }
        })
    }

    // 表字段删除
    $fieldWrap.on("click", ".JS_btnDelTable", function(){
        $(this).parents(".table-item").remove();
    })

    // 获取已选表字段options
    var fieldOption ='';
    function getTableOption(tableName){
        var fieldObj = $fieldWrap.find(".table-item");
        fieldObj.each(function() {
            var _tableName = $(this).attr('data-tableName');
            if(tableName == _tableName){
                fieldOption = $(this).find('select').html();
            }
        });
        return fieldOption;
    }

    // 添加取值字段内容
    function addCondition(tableName, fieldName, fieldNote, paramId){
        $("#paramWrap").empty();    
        getTableOption(tableName);
        var $paramTable = $('<div style="margin:0 20px;"><table class="table table-bordered"><thead><tr><th>值</th><th>字段</th><th>过滤条件</th></tr></thead><tbody></tbody></table></div>')
        
        $("#paramWrap").append($paramTable);

        // 添加条件字段
        $paramTable.on('click', '.JS_addCondition', function(){
            var $conditionItem = $('<tr class="condition-item"><td><select class="JS_conditionField">'+ fieldOption +'</select>'+ conditionSelect +'<select class="JS_conditionValue" id=""></select></td><td><span class="JS_delCondition btn btn-danger btn-xs">删除条件</span></td></tr>')
            $paramTable.find('.condition-wrap tbody tr:last').before($conditionItem);
        })

        // 删除条件字段
        $paramTable.on('click', '.JS_delCondition', function(){
            $(this).closest('tr').remove();
        })
    }


    // 获取字段条件
    var $paramConditionItem ='';
    var paramKey ='';
    function getCondition(layero){
        var _this           = $(layero).find(".param-item");
        var _paramId        = _this.find(".JS_paramId").text();
        var _fileNote       = _this.find(".JS_fieldNote").text();
        var _tableName      = _this.attr('data-tablename');
        var _valFieldName   = _this.attr('data-fieldname');
        var conditionsObj   = _this.find(".condition-item");
        var _condition = {};
        conditionsObj.each(function() {
            var _conFieldName = $(this).find('.JS_conditionField').find(':selected').val();
            var _conFieldRelate = $(this).find('.JS_conditionRelate').find(':selected').val();
            var _conFieldValue = $(this).find('.JS_conditionValue').find(':selected').val();
            var _conCondition = _conFieldRelate + "'"+ _conFieldValue + "'";
            if(!_conFieldName == ''){
                if(typeof _condition[_conFieldName] == 'undefined'){
                    _condition[_conFieldName] = _conCondition;
                }else{
                    _condition[_conFieldName] = _condition[_conFieldName]+'||'+_conCondition;
                }
            }
        });

        var _paramItem = {'table': _tableName, 'note': _fileNote, 'field':_valFieldName, 'condition':_condition};
        var paramItem = {};
        paramItem[_paramId] = _paramItem;

        $paramConditionItem = $('<span class="JS_btnDelParam delparam"><i class="fa fa-close"></i></span><span>'+ _paramId +'</span><textarea style="display:none">'+ JSON.stringify(paramItem) + '</textarea>');
        paramKey = _paramId;
    }


    var conditionSelect = '<select class="JS_conditionRelate">'+
        '<option value="=">=</option>'+
        '<option value=">">></option>'+
        '<option value=">=">>=</option>'+
        '<option value="<"><</option>'+
        '<option value="<="><=</option>'+
        '<option value="in">包含</option>'+
        '</select>';

    // "param": [
    //     {
    //         "T1": {
    //             "table": "T_NTTJ_DATA_2016",
    //             "note": "总量",
    //             "field": "ZL",
    //             "condition": {}
    //         }
    //     }
    // ],
    // <span class="field-item" data-fieldname="'+ fields[key].name +'">'+ fields[key].note +'</span>

    $("#paramWrap").on('change', '.JS_conditionField', function(){
        var fieldName = $(this).val();
        var tableName = $(this).parents(".param-item").attr("data-tablename");
        var _this = $(this);
        var columnSelect = _this.parent('td').find(".JS_conditionValue");
        columnSelect.empty();
        $.ajax({
            type:"POST",
            dataType:"jsonp",
            jsonp:"callback",
            url: GetUrl + "/trueDataController/columnVal.do?table="+tableName+"&column="+fieldName,
            cache: false,
            async: false,
            success:function(msg){
                var values = msg.data;
                console.log(values)
                var fieldOption = '';
                for(key in values){
                    columnSelect.append(new Option(values[key], values[key]));
                }
            }
        });
    })

    // 点击选择取值字段
    var paramIndex = 1;
    $fieldWrap.on("click", ".field-item", function(){
        $(this).addClass('checked');
        var tableName   = $(this).parents(".table-item").attr("data-tableName");
        var fieldName   = $(this).attr("data-fieldName");
        var fieldNote   = $(this).text();
        var paramId     = 'T'+paramIndex;

        // getCondition(layero);
        var $paramItem = $('<div class="paramval-item" data-paramid="'+ paramId +'" data-tablename="'+ tableName +'" data-fieldname="'+ fieldName +'" data-fieldnote="'+ fieldNote +'"><span class="JS_btnDelParam delparam"><i class="fa fa-close"></i></span><span>'+ paramId +'<br /><b>'+ fieldNote +'</b></span></div>');
        
        $paramWrap.append($paramItem);

        // setFunction(paramKey);



        // addCondition(tableName, fieldName, fieldNote, paramId);

        // getTableOption(tableName);

        // // 插入取值字段
        // var $paramItem = $('<tr class="param-item" data-tablename="'+ tableName +'" data-fieldname="'+ fieldName +'"><td class="JS_paramId" style="vertical-align: middle;">'+ paramId +'</td><td class="JS_fieldNote" style="vertical-align: middle;">'+ fieldNote +'</td><td style="padding:0;" class="conditionWrap"></td></tr>')
        // // 生成字段条件table
        // $("#paramWrap").find('tbody').eq(0).append($paramItem);

        
        // var conditionTable = $('<table class="condition-wrap table" style="margin-bottom:0;"><tbody>'+
        //         '<tr class="condition-item">'+
        //         '<td><select class="JS_conditionField">'+ fieldOption +'</select>'+ conditionSelect + '<select class="JS_conditionValue" id=""></select>' +
        //         '<td><span class="JS_delCondition btn btn-danger btn-xs">删除条件</span></td>'+
        //         '</tr><tr><td colspan="2"><span class="JS_addCondition btn btn-primary btn-xs">添加条件</span></td></tr></tbody></table>')
        // $("#paramWrap").find('.conditionWrap').append(conditionTable);


        paramIndex ++ ;

        
        // layer.open({
        //     type: 1,
        //     area: ['800px', '400px'],
        //     title: '插入值', 
        //     content: $("#paramWrap"), 
        //     btn: ['确定', '取消'],
        //     yes: function(indexa, layero){
        //         getCondition(layero);
        //         var $pp = $('<div class="paramval-item"></div>').append($paramConditionItem);
        //         $paramWrap.append($pp);

        //         setFunction(paramKey);
                
        //         layer.close(indexa);
        //     }
        // });

        setFunction();

        
    })

    // 计算公式
    function setFunction(paramKey){
        if($functionWrap.find('input').length){
            var _function = $functionWrap.find('input').val();
            $functionWrap.find('input').val(_function + paramKey);
        } else{
            $functionWrap.append('<p><span>计算公式：</span><input class="JS_inputResult" type="text" placeholder="计算公式" /><span class="JS_btnFunctionSum btn btn-primary btn-xs">求和</span><span class="JS_btnFunctionAvg btn btn-primary btn-xs">平均值</span></p>')
                    .find('input').val(paramKey);
            $tagResultWrap.append('<p>结果预览：<span class="JS_btnTagTest btn btn-primary btn-xs">测试</span> <span class="JS_tagValue tags"></span></p>');
        }
    }

    // 删除取值字段
    $paramWrap.on("click", ".JS_btnDelParam", function(){
        $(this).parent(".paramval-item").remove();
        var params = $paramWrap.find(".paramval-item");
        var tables = $fieldWrap.find('.table-item');
        var tableName = $(this).parent(".paramval-item").attr('data-tablename');
        var fieldName = $(this).parent(".paramval-item").attr('data-fieldname');
        tables.each(function(index, el) {
            var _table = $(this);
            if(_table.attr('data-tablename') == tableName){
                var fields = _table.find('.field-item');
                fields.each(function(index, el) {
                    var _field = $(this);
                    if(_field.attr('data-fieldname') == fieldName){
                        _field.removeClass('checked');
                    }
                });
            }
        });

        return false;
    })

    // 取值字段hover
    $paramWrap.on({
        mouseenter: function () {
            $(this).find(".JS_btnDelParam").show();
        },
        mouseleave: function () {
            $(this).find(".JS_btnDelParam").hide();
        }
    }, ".paramval-item"); 


    // 求和按钮
    $functionWrap.on("click", ".JS_btnFunctionSum", function(){
        var params = $paramWrap.find('.paramval-item');
        var length = params.length;
        var paramids = 'sum(';
        params.each(function(index) {
            var paramid = $(this).attr('data-paramid');
            // paramids.push(paramid);
            if(index+1 == length){
                paramids += paramid;
            }else{
                paramids += paramid+'+';
            }
            
        });
        paramids += ')'
        $functionWrap.find('input').val(paramids);
    })


    // 平均值按钮
    $functionWrap.on("click", ".JS_btnFunctionAvg", function(){
        var params = $paramWrap.find('.paramval-item');
        var length = params.length;
        var paramids = 'avg(';
        params.each(function(index) {
            var paramid = $(this).attr('data-paramid');
            // paramids.push(paramid);
            if(index+1 == length){
                paramids += paramid;
            }else{
                paramids += paramid+',';
            }
            
        });
        paramids += ')'
        $functionWrap.find('input').val(paramids);
    })


	//重定义弹出层大小
	function getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY}else{if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight}}var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth}else{windowWidth=self.innerWidth}windowHeight=self.innerHeight}else{if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight}else{if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight}}}if(yScroll<windowHeight){var pageHeight=windowHeight}else{var pageHeight=yScroll}if(xScroll<windowWidth){var pageWidth=xScroll}else{var pageWidth=windowWidth}var arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize}
   
    function layerIn(argsObj){
    	var pageSize = getPageSize();
    	// 清空弹框内容
        clearTagsWrap();
        // 获取表数据
        getModelList(argsObj);

        layer.open({
            type: 1,
            area: [pageSize[2]-200+'px', pageSize[3]-100+'px'],
            title: '插入标签', 
            content: $('#tagWrap'), 
            btn: ['确定', '取消'],
            yes: function(index){
                creatTagJSON();
                if($.fn.GL.getValue('_editing')===1){
                	var tagId = $.fn.GL.getValue('_openedTagId');
                }else{
                	var tagId = getUniqeId();
                }
                
                var a = JSON.stringify(tagJSON);
                $.ajax({
                    type:"POST",
                    data:a,
                    dataType:"jsonp",
                    jsonp:"callback",
                    url:GetUrl + "/formulaController/getResult.do?function="+encodeURIComponent(a),
                    success:function(msg){
                        var val;
                        if(msg.success){
                            val = msg.data[0].tag;
                        }else{
                            val = msg.error;
                        }
                         if ( $tagResultWrap.find(".JS_tagValue").text() != val){
                            layer.alert('请先测试数据！');
                        } else{
                            // var tagValue = $tagResultWrap.find(".JS_tagValue").text();
                            // var s = '<b class="tags" data-id="'+ tagId +'"><i class="tagtmp">'+ tagValue +'</i><i class="tagtruedata"><!--TrueDATA['+a+']--></i></b>';
                            // var s ='<b><i class="tagtmp">'+ tagValue +'</i><i class="tagtruedata"><!--ee--></i></b>'

							var len = $("#tagTem").find("#"+tagId).length;
							if($.fn.GL.getValue('_editing')===1){
								$("#tagTem").find("#"+tagId).empty().append(a);
								
								//remove
								var $delete = $('.wangeditor-menu-img-trash-o');
								$delete.click();
								
	                            //insert
								var tagValue = $tagResultWrap.find(".JS_tagValue").text();
								var s = '<b class="tags" data-id="'+ tagId +'">'+ tagValue +'</b>';
								
	                            // 执行命令
	                            argsObj.editor.command(argsObj.e, 'insertHtml', s);
							}else{
								var tagTem =  '<textarea style="display:none" id="'+tagId+'">'+a+'</textarea>';
								$("#tagTem").append(tagTem);
								
								//insert
								var tagValue = $tagResultWrap.find(".JS_tagValue").text();
								var s = '<b class="tags" data-id="'+ tagId +'">'+ tagValue +'</b>';
								
	                            // 执行命令
	                            argsObj.editor.command(argsObj.e, 'insertHtml', s);
							}
                            
							
                            
							//绑定中的数据存入key
							$.fn.GL.setValue(tagId,$.fn.GL.getValue('_Current'));

                            layer.close(index);
                            $.fn.GL.setValue('_editing',0);
                            $.fn.GL.setValue('_Current',{});
                        }
                    }
                });         
            },
            cancel :function(){
            	$.fn.GL.setValue('_editing',0);
                $.fn.GL.setValue('_Current',{});
            }
        });
    }
   
    // 创建tag 标签
    E.createMenu(function (check) {
    
        var menuId = 'tags';
        if (!check(menuId)) {
            return;
        }
        var editor = this;
        
        // 创建 menu 对象
        var menu = new E.Menu({
            editor: editor,
            id: menuId,
            title: '插入标签',

            // 正常状态和选中装下的dom对象，样式需要自定义
            $domNormal: $('<a href="#" tabindex="-1"><i class="wangeditor-custom-icon-tags"></i></a>'),
            $domSelected: $('<a href="#" tabindex="-1" class="selected"><i class="wangeditor-custom-icon-tags"></i></a>')
        });

		
		

        // 点击菜单
        menu.clickEvent = function (e) {
        	$.fn.GL.setValue('_editing',0);
        	layerIn({editor:editor,e:e});
        }//clickEvent end

        // 增加到editor对象中
        editor.menus[menuId] = menu;
    });
    
	//数据读取
	function loadDate(tmpTagId){
		//start status
		var readData = $.fn.GL.getValue(tmpTagId)
		if(readData){
        	var data1 = readData.data1
        	,data2 = readData.data2
        	,data3 = readData.data3
        	,data4 = readData.data4;
        	//step.1
        	if(data1){
        		$tableWrap.find("select").change();
        		
        		//step.2
        		if(data2){
        			$groupWrap.find(".label-item[data-guid='"+data2+"']").click();
        		}
        		
        		//step.3
        		if(data3){
        			$fieldWrap.find(".label-item[data-paramid='"+data3+"']").click();
        		}
        		
        		//step.4
        		if(data4.conditionType){
        			$conditionWrap.find(".JS_conditionDate").change();
        		}
        		if(data4.t_year){
        			$conditionWrap.find("select.JS_condYear").change();
        		}
        		if(data4.t_month){
        			$conditionWrap.find("select.JS_condMonth").change();
        		}
        		if(data4.t_quarter){
        			$conditionWrap.find("select.JS_condQuarter").change();
        		}
        		
        		//step.5
        	}
    	}
	}
	
    // tag toolbar
    E.plugin(function () {
        var editor = this;
        var txt = editor.txt;
        var $txt = txt.$txt;
        // 说明：设置了 max-height 之后，$txt.parent() 负责滚动处理
        var $currentTxt = editor.useMaxHeight ? $txt.parent() : $txt;
        var $currentTag;

        // 用到的dom节点
        var isRendered = false;
        var $toolbar = $('<div class="txt-toolbar"></div>');
        var $triangle = $('<div class="tip-triangle"></div>');
        var $delete = $('<a href="#"><i class="wangeditor-menu-img-trash-o"></i></a>');
        var $edit = $('<a href="#"><i class="wangeditor-custom-icon-edit"></i></a>');
        //id前缀
        

        // 渲染到页面
        function render() {
            if (isRendered) {
                return;
            }
            
            // 绑定事件
            bindEvent();

            // 拼接 渲染到页面上
            $toolbar.append($triangle)
                    .append($delete)
                    .append($edit);
            editor.$editorContainer.append($toolbar);
            isRendered = true;
        }

        // 绑定事件
        function bindEvent() {
            // 统一执行命令的方法
            var commandFn;
            function command(e, callback) {
                if (commandFn) {
                    editor.customCommand(e, commandFn, callback);
                }
            }

            // 删除
            $delete.click(function (e) {
                commandFn = function () {
                    $currentTag.remove();
                };
                command(e, function () {
                    setTimeout(hide, 100);
                });
            });

            $edit.click(function(e) {
                // var random = E.random();
                // var rangeElem = editor.getSelfOrParentByName('i','tags');
                // console.log(rangeElem);

                var ct = $currentTag;
                var tagId = $currentTag.attr('data-id');
            	$.fn.GL.setValue('_openedTagId',tagId);

                // var tag = JSON.parse($("#"+$currentTag.attr('data-id')).val());
                var tag ='';
                if($("#"+$currentTag.attr('data-id')).length>0){
                    tag = JSON.parse($("#"+tagId).val());
                } else{
                    var taglabel = $currentTag.html();
                    var star = taglabel.indexOf("<!--TrueDATA[");
                    tag = JSON.parse(taglabel.slice(star+13,taglabel.length-4));
                }

//              $.each(tag.param, function(key, value){
//                  var paramKey = Object.keys(value)[0];
//
//                  $paramConditionItem = $('<div class="paramval-item"><span class="JS_btnDelParam delparam"><i class="fa fa-close"></i></span><span>'+ paramKey +'</span><textarea style="display:none">'+ JSON.stringify(value) + '</textarea></div>');
//                  //计算可选标签已隐藏
////                  $paramWrap.append($paramConditionItem);
// 
//              });

//              var paramKey = tag.result.tag;
                //计算公式已隐藏
//              setFunction(paramKey);

                //rewrite
                $.fn.GL.setValue('_editing',1);
                layerIn({editor:editor,e:e,tagId:tagId});
                loadDate(tagId);
            });//edit click end
        }

        // 显示 toolbar
        function show() {
            if (editor._disabled) {
                // 编辑器已经被禁用，则不让显示
                return;
            }
            if ($currentTag == null) {
                return;
            }
            $(".tags").removeClass('clicked');
            $currentTag.addClass('clicked');
            var tagPosition = $currentTag.position();
            var tagTop = tagPosition.top;
            var tagLeft = tagPosition.left;
            var tagHeight = $currentTag.outerHeight();
            var tagWidth = $currentTag.outerWidth();

            // --- 定位 toolbar ---

            // 计算初步结果
            var top = tagTop + tagHeight;
            var left = tagLeft;
            var marginLeft = 0;

            var txtTop = $currentTxt.position().top;
            var txtHeight = $currentTxt.outerHeight();
            if (top > (txtTop + txtHeight)) {
                // top 不得超出编辑范围
                top = txtTop + txtHeight;
            }

            // 显示（方便计算 margin）
            $toolbar.show();

            // 计算 margin
            var width = $toolbar.outerWidth();
            marginLeft = tagWidth / 2 - width / 2;

            // 定位
            $toolbar.css({
                top: top + 5,
                left: left,
                'margin-left': marginLeft
            });
            // 如果定位太靠左了
            if (marginLeft < 0) {
                // 得到三角形的margin-left
                $toolbar.css('margin-left', '0');
                $triangle.hide();
            } else {
                $triangle.show();
            }
        }
        
        // 隐藏 toolbar
        function hide() {
            if ($currentTag == null) {
                return;
            }
//          $currentTag.removeClass('clicked');
//          $currentTag = null;
            $toolbar.hide();
        }

        // click tag 事件
        $currentTxt.on('click', '.tags', function (e) {
            var $tag = $(e.currentTarget);

            // 渲染
            render();

            if ($currentTag && ($currentTag.get(0) === $tag.get(0))) {
                setTimeout(hide, 100);
                return;
            }

            // 显示 toolbar
            $currentTag = $tag;
            show();

            // 阻止冒泡
            e.preventDefault();
            e.stopPropagation();
            
        }).on('click keydown scroll', function (e) {
            setTimeout(hide, 100);
        });
        E.$body.on('click keydown scroll', function (e) {
            setTimeout(hide, 100);
        });
    });


    
   

})();